package cn.kz.keepass_android;

import android.graphics.BitmapFactory;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.List;

import de.slackspace.openkeepass.domain.Entry;

public class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder> {
    private List<Entry> datas = new ArrayList<>();
    private View.OnClickListener listener;

    public MyAdapter(List<Entry> datas) {
        this.datas = datas;
    }

    public void setListener(View.OnClickListener listener) {
        this.listener = listener;
    }

    //创建新View，被LayoutManager所调用
    @Override
    public ViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
        View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.pass_item, viewGroup, false);
        if (listener != null) {
            view.setOnClickListener(listener);
        }
        ViewHolder vh = new ViewHolder(view);
        return vh;
    }

    //将数据与界面进行绑定的操作
    @Override
    public void onBindViewHolder(ViewHolder viewHolder, int position) {
        Entry entry = datas.get(position);
        viewHolder.title.setText(entry.getTitle());
        viewHolder.username.setText(entry.getUsername());
        viewHolder.icon.setImageBitmap(BitmapFactory.decodeByteArray(entry.getIconData(), 0, entry.getIconData().length));
    }

    //获取数据的数量
    @Override
    public int getItemCount() {
        return datas.size();
    }

    public void setEntries(List<Entry> entries) {
        datas = entries;
    }

    public void notifyDataChanged() {
        this.notifyDataSetChanged();
    }

    public Entry get(int position) {
        return datas.get(position);
    }


    //自定义的ViewHolder，持有每个Item的的所有界面元素
    static class ViewHolder extends RecyclerView.ViewHolder {
        ImageView icon;
        TextView title, username;

        public ViewHolder(View view) {
            super(view);
            icon = (ImageView) view.findViewById(R.id.icon);
            title = (TextView) view.findViewById(R.id.title);
            username = (TextView) view.findViewById(R.id.username);
        }
    }
}